<?php

namespace Icsoc\SecurityBundle\Controller;

use Aliyun\MNS\Client;
use Aliyun\MNS\Requests\SendMessageRequest;
use Icsoc\CoreBundle\Controller\BaseController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Predis\Client as RedisClient;

/**
 * 高级设置
 * Class RoleController
 * @package Icsoc\SecurityBundle\Controller
 */
class DevelopersController extends BaseController
{
    /**
     * 开发者功能
     * @return Response
     */
    public function indexAction()
    {
        $vccId = $this->getVccId();
        $conn = $this->container->get('doctrine.dbal.default_connection');
        $data = $conn->fetchAssoc("SELECT open_api,remote_password FROM cc_ccods WHERE vcc_id=$vccId");
        if (empty($data['remote_password'])) {
            $random = random_bytes(10);
            $random = md5($random);
            try {
                $conn->update('cc_ccods', array('remote_password' => $random), array('vcc_id' => $vccId));
                $data['remote_password'] = $random;
            } catch (\Exception $e) {
                $data['remote_password'] = '点击更换生成密匙';
            }
        }

        return $this->render('IcsocSecurityBundle:Developers:Index.html.twig', array(
            'openApi' => $data['open_api'],
            'remotePassword' => $data['remote_password'],
        ));
    }

    /**
     * 打开关闭API、更换密码
     * @param Request $request
     * @return JsonResponse
     */
    public function validationAction(Request $request)
    {
        $vccId = $this->getVccId();
        $conn = $this->container->get('doctrine.dbal.default_connection');
        $pass = $request->get('pass', '');
        $work = $request->get('work', '');
        $api = $request->get('api', '');
        if (!empty($pass)) {
            $pass = md5($pass);
            $md5Pass = $conn->fetchColumn("SELECT admin_password FROM cc_ccods WHERE vcc_id=$vccId");
            if (hash_equals($pass, $md5Pass)) {
                $random = random_bytes(10);
                $random = md5($random);
                switch ($work) {
                    case "api":
                        if (!empty($api)) {
                            try {
                                $conn->update('cc_ccods', array('open_api'=>$api), array('vcc_id'=>$vccId));
                            } catch (\Exception $e) {
                                return new JsonResponse(array('error'=>1, 'message'=>'操作失败'));
                            }

                            return new JsonResponse(array('error'=>2, 'message'=>$api));
                        }

                        return new JsonResponse(array('error'=>1, 'message'=>'操作失败'));
                        break;
                    case "pass":
                        try {
                            $conn->update('cc_ccods', array('remote_password'=>$random), array('vcc_id'=>$vccId));
                        } catch (\Exception $e) {
                            return new JsonResponse(array('error'=>1, 'message'=>'操作失败'));
                        }
                        break;
                }

                return new JsonResponse(array('error'=>0, 'message'=>$random));
            }

            return new JsonResponse(array('error'=>1, 'message'=>'密码不正确'));
        }

        return new JsonResponse(array('error'=>1, 'message'=>'没有密码'));
    }

    /**
     * 下载任务管理
     * @return Response
     */
    public function downloadAction()
    {
        return $this->render('IcsocSecurityBundle:Developers:download.html.twig');
    }
    /**
     * 获取数据
     * @param Request $request
     * @return array|JsonResponse
     */
    public function downloadDataAction(Request $request)
    {
        $param['vcc_id'] = $this->getVccId();
        $param['page'] = $request->get('page', 1);
        $param['rows'] = $request->get('rows', 10);
        $param['order'] = $request->get('sord', 'desc');
        $param['field'] = $request->get('sidx', '');
        $param['startTime'] = $request->get('startTime', '');
        $param['endTime'] = $request->get('endTime', '');


        $result = $this->get('icsoc_data.model.develop')->getDownload($param);

        if (isset($result['code']) && $result['code'] == 200) {
            return new JsonResponse($result);
        }

        return new JsonResponse(
            array(
                'code'=>$result['code'],
                'message'=>$result['message'],
                'records' => 0,
                'page' => 0,
                'total' => 0,
                'rows'=>array(),
            )
        );
    }

    /**
     * 实时进度
     * @param Request $request
     * @return array|JsonResponse
     */
    public function uploadDataAction(Request $request)
    {
        $url = $this->container->getParameter('create_download_file_url');
        $newUrl = $this->container->getParameter('new_create_download_file_url');
        $tokenId = $request->get('tokenId', '');
        $newTokenId = $request->get('newTokenId', '');
        $allId = $request->get('allId', '');

        $returnData = array();

        $allUrl = array();  //文件成生后会生成下载路径
        $useTime = array(); //开始生成时间
        $fileSize = array(); //文件大小
        $datacount = array(); //数据量
        $msgTokenId = array();//生成失败的数据
        $data = array();
        $newData = array();
        if (!empty($tokenId)) {
            $data = $this->get('icsoc_data.model.develop')->getProgress($url, $tokenId);
        }
        if (!empty($newTokenId)) {
            $newData = $this->get('icsoc_data.model.develop')->getNewProgress($newUrl, $newTokenId);
        }
        $data = array_merge_recursive($data, $newData);
        $allId = array_flip($allId);   //key val交换方便比较，获得有值的数组,过滤没有数据的数组
        foreach ($allId as $key => $val) {
            foreach ($data['data'] as $k => $v) {
                if ($key == $k) {
                    $returnData[$val] = $v;
                    $allUrl[$val] = $data['allUrl'][$k];
                    $useTime[$val] = $data['use_time'][$k];
                    $fileSize[$val] = $data['file_size'][$k];
                    $datacount[$val] = $data['datacount'][$k];
                }
            }
        }
        //处理生成失败的数据
        if (!empty($data['msg_token_id'])) {
            foreach ($allId as $key => $val) {
                foreach ($data['msg_token_id'] as $v) {
                    if ($key == $v) {
                        $msgTokenId[$val] = $key;
                    }
                }
            }
        }

        return new JsonResponse(array(
            'data' => $returnData,
            'url' => $allUrl,
            'use_time' => $useTime,
            'file_size' => $fileSize,
            'datacount' => $datacount,
            'msg_token_id' => $msgTokenId,
        ));
    }

    /**
     * 通话结果推送
     * @return Response
     */
    public function callPushAction()
    {
        $vccId = $this->getVccId();
        $conn = $this->container->get('doctrine.dbal.default_connection');
        $data = $conn->fetchAssoc("SELECT conn_push,conn_push_url,hangup_push,push_url FROM cc_ccods WHERE vcc_id=$vccId");

        return $this->render('IcsocSecurityBundle:Developers:callpush.html.twig', array(
            'pushInfo' => $data,
        ));
    }


    /**
     * 设置打开关闭通话结果推送
     * @param Request $request
     * @return JsonResponse
     */
    public function setCallPushAction(Request $request)
    {
        $vccId = $this->getVccId();
        $conn = $this->container->get('doctrine.dbal.default_connection');
        $pass = $request->get('pass', '');
        $connPush = $request->get('conn_push', 2);
        $hangupPush = $request->get('hangup_push', 2);
        $connPushUrl = $request->get('conn_push_url', '');
        $pushUrl = $request->get('push_url', '');

        $data['conn_push'] = $connPush;
        $data['hangup_push'] = $hangupPush;
        if ($connPush == 1 && empty($connPushUrl)) {
            return new JsonResponse(array('error'=>true, 'msg'=>'推送url没有值'));
        } else if($connPush == 1 && !empty($connPushUrl)) {
            $data['conn_push_url'] = $connPushUrl;
        }
        if ($hangupPush == 1 && empty($pushUrl)) {
            return new JsonResponse(array('error'=>true, 'msg'=>'推送url没有值'));
        } else if ($hangupPush == 1 && !empty($pushUrl)) {
            $data['push_url'] = $pushUrl;
        }
        $pass = md5($pass);
        $md5Pass = $conn->fetchColumn("SELECT admin_password FROM cc_ccods WHERE vcc_id = ?", array($vccId));
        if (hash_equals($pass, $md5Pass)) {
            $conn->update('cc_ccods', $data, array('vcc_id'=>$vccId));

            return new JsonResponse(array('error'=>false, 'msg'=>'修改成功'));
        } else {
            return new JsonResponse(array('error'=>true, 'msg'=>'密码不正确'));
        }
    }

    /**
     * 通话结果推送页面
     * @return Response
     */
    public function callRecordAction()
    {
        return $this->render('IcsocSecurityBundle:Developers:callrecord.html.twig');
    }

    /**
     * 获取数据
     * @param Request $request
     * @return array|JsonResponse
     */
    public function callRecordDataAction(Request $request)
    {
        $param['vcc_id'] = $this->getVccId();
        $param['page'] = $request->get('page', 1);
        $param['rows'] = $request->get('rows', 10);
        $param['order'] = $request->get('sord', 'desc');
        $param['field'] = $request->get('sidx', 'id');
        $param['phone'] = $request->get('phone', '');
        $param['sendRes'] = $request->get('sendRes', '');
        $param['sendType'] = $request->get('sendType', '');


        $result = $this->get('icsoc_data.model.develop')->getRecord($param);

        if (isset($result['code']) && $result['code'] == 200) {
            return new JsonResponse($result);
        }

        return new JsonResponse(
            array(
                'code'=>$result['code'],
                'message'=>$result['message'],
                'records' => 0,
                'page' => 0,
                'total' => 0,
                'rows'=>array(),
            )
        );
    }

    /**
     * 重新推送失败的数据；
     * @return JsonResponse
     */
    public function repushCallAction()
    {
        //先需要查询是否存在重推中
        $conn = $this->get('doctrine.dbal.default_connection');
        $vccId = $this->getVccId();
        $count = $conn->fetchColumn(
            "SELECT count(id) FROM win_push_record WHERE send_res = 4 AND vcc_id = ?",
            array($vccId)
        );
        if (!empty($count)) {
            return new JsonResponse(array('error'=>true, 'msg'=>'数据存在状态为重推中,不能重复推送'));
        }
        $mnsConfig = $this->container->getParameter('ali_mns');
        $mnsClient = new Client($mnsConfig['endpoint'], $mnsConfig['key'], $mnsConfig['secret']);
        $mnsQue = $mnsClient->getQueueRef($mnsConfig['quename']);

        $vccInfos = $conn->fetchAssoc("SELECT push_url,hangup_push,conn_push,conn_push_url FROM cc_ccods WHERE vcc_id = ?", array($vccId));
        if ($vccInfos['hangup_push'] != 1 && $vccInfos['conn_push'] != 1) {
            return new JsonResponse(array('error'=>true, 'msg'=>'你未开启推送'));
        }
        $where = '';
        if ($vccInfos['hangup_push'] == 1 && $vccInfos['conn_push'] != 1) {
            $where .= ' AND call_type in(1,2) ';
        }
        if ($vccInfos['hangup_push'] != 1 && $vccInfos['conn_push'] == 1) {
            $where .= ' AND call_type = 3 ';
        }
        //查找出推送失败的
        $list = $conn->fetchAll(
            "SELECT id,send_params,call_type FROM win_push_record 
            WHERE send_res = 2 AND vcc_id = ? $where ORDER BY send_start_time DESC LIMIT 1000",
            array($vccId)
        );

        $redis = new RedisClient(
            array(
                'scheme'=>'tcp',
                'host'=> $this->container->getParameter('redis.host'),
                'port'=> $this->container->getParameter('redis.port'),
                'password'=> $this->container->getParameter('redis.password'),
                'database'=> 4, //这个根据目前配置的
            )
        );
        try {
            foreach ($list as $data) {
                $sendParams = json_decode($data['send_params'], true);
                $sendParams['lastId'] = $data['id'];
                if ($data['call_type'] == 3) {
                    $sendParams['url'] = $vccInfos['push_url'];
                } else {
                    $sendParams['url'] = $vccInfos['conn_push_url'];
                }
                $redisKey = sprintf("push_%s", $sendParams['data']['callid']);
                $redis->del($redisKey); //删除掉以前的技术器
                $message  = new SendMessageRequest(json_encode($sendParams, JSON_UNESCAPED_UNICODE));
                $mnsQue->sendMessage($message); //需要加一个
                $conn->update('win_push_record', array('send_res'=>4), array('id'=>$data['id']));
            }

            return new JsonResponse(array('error'=>false, 'msg'=>'ok'));
        } catch (\Exception $e) {
            $this->get('logger')->error(sprintf("重新推送数据发生异常【%s】", $e->getMessage()));

            return new JsonResponse(array('error'=>true, 'msg'=>'推送失败'));
        }
    }

    /**
     * 分机注册信息
     * @return Response
     */
    public function phoneInfoAction()
    {
        return $this->render('IcsocSecurityBundle:Developers:phoneInfo.html.twig');
    }

    /**
     * 分机注册信息数据
     * @param Request $request
     * @return Response
     */
    public function phoneInfoDataAction(Request $request)
    {
        $page = $request->get('page', 1);
        $rows = $request->get('rows', 10);
        $sord = $request->get('sord', 'asc');
        $sidx = $request->get('sidx', 'id');
        $phone = $request->get('phone', '');
        $phoneType = $request->get('phonetype', '');
        $info = array(
            'pagination'=>array('rows'=>$rows, 'page'=>$page),
            'filter'=> array('phone'=>$phone, 'phonetype'=>$phoneType),
            'sort'=>array('order' => $sord, 'field' => $sidx),
        );
        $vccCode = $this->getUser()->getVccCode();
        $list = $this->get('icsoc_data.model.develop')->getSipPhone(array('vcc_code'=>$vccCode, 'info'=>json_encode($info)));

        return new JsonResponse(
            array(
                'total' => isset($list['totalPage']) ? $list['totalPage'] : 0,
                'page' => isset($list['page']) ? $list['page'] : 1,
                'records' => isset($list['total']) ? $list['total'] : 0,
                'rows' => $list['data'],
                'code' => isset($list['code']) ? $list['code'] : '',
                'message' => isset($list['message']) ? $list['message'] : '',
            )
        );
    }

    /**
     * 挂机短信
     */
    public function hangUpSmsAction()
    {
        $vccId = $this->getVccId();
        $swjHangupSms = $this->get('icsoc_data.model.develop')->getSwjHangupSms($vccId);
        $endsms = $this->get('icsoc_data.model.develop')->getEndsms($vccId);
        $data = array_merge($swjHangupSms, $endsms);
        $data['is_connect'] = isset($data['is_connect']) ? $data['is_connect'] : 0;
        $data['connect_sms'] = isset($data['connect_sms']) ? $data['connect_sms'] : '';
        $data['is_busy'] = isset($data['is_busy']) ? $data['is_busy'] : 0;
        $data['busy_sms'] = isset($data['busy_sms']) ? $data['busy_sms'] : '';
        $data['endsms_type'] = isset($data['endsms_type']) ? $data['endsms_type'] : 0;
        $data['endsms_phone'] = isset($data['endsms_phone']) ? $data['endsms_phone'] : '';
        $data['vcc_signature'] = isset($data['vcc_signature']) ? $data['vcc_signature'] : '';

        return $this->render(
            'IcsocReportBundle:Detail:hangUpSms.html.twig',
            array('data' => $data)
        );
    }

    /**
     * 更新挂机短信配置信息
     */
    public function updateHangUpSmsAction(Request $request)
    {
        $vccId = $this->getVccId();

        $hangupSms['is_connect'] = $request->get('is_connect', 0);
        $hangupSms['connect_sms'] = $request->get('connect_sms', '');
        $hangupSms['is_busy'] = $request->get('is_busy', 0);
        $hangupSms['busy_sms'] = $request->get('busy_sms', '');
        $hangupSms['vcc_signature'] = $request->get('vcc_signature', '');

        $endSms['endsms_type'] = $request->get('endsms_type', 0);
        $endSms['endsms_phone'] = $request->get('endsms_phone', '');

        $msgDetail = "修改成功";
        $type = "success";
        $swjHangupSms = $this->get('icsoc_data.model.develop')->updateSwjHangupSms($vccId, $hangupSms);
        if ($swjHangupSms['code'] != 200) {
            $msgDetail = '修改失败';
            $type = "error";
            goto end;
        }
        $ccods = $this->get('icsoc_data.model.develop')->updateEndSms($vccId, $endSms);
        if ($ccods['code'] != 200) {
            $msgDetail = '部分修改失败';
            $type = "error";
        }

        end:
        $data = array(
            'data'=>array(
                'msg_detail'=>$msgDetail,
                'type'=>$type,
                'link' => array(
                    array(
                        'text'=> '挂机短信',
                        'href'=>$this->generateUrl("icsoc_security_develop_hang_up_sms"),
                    ),
                )
            )
        );

        return $this->redirect($this->generateUrl('icsoc_ui_message', $data));
    }
}
